<?php

namespace app\admin\controller;

use think\Db;
use think\Session;
use think\Validate;
use think\Request;
use GatewayClient\Gateway;
use app\api\model\Task;


class Article extends Common
{
    public function index()
    {
        /*$typeiddb = Db::name('dymanic_category')->where('is_hide', 0)->order('des desc,id asc')->select();
        $this->assign('typeid', $typeiddb);*/

        $type = input('type/d') ?: 3;
    
        $where = ['t1.type' => $type];

        $this->assign('type', $type);

        $shenhe = input('shenhe/d');

        if ($shenhe === null) {
            $shenhe = 1;
        }
        $where['t1.shenhe'] = $shenhe;
        $this->assign('shenhe', $shenhe);


        $typeid = input('param.search_typeid');
        $search_name = input('param.search_name');
        if ($search_name) {
            $where['t1.content'] = ['like', '%' . $search_name . '%'];
        }
        $order = input('order') ? input('order') : 'desc';
        if ($order == 1) {
            $order = 'desc';
        } else if ($order == 2) {
            $order = 'asc';
        }

        if ($typeid) {
            $where['t1.category_id'] = $typeid;
        }

        $data = Db::name('dymanic t1')
            ->field('t1.*, t2.name, t3.name username, t3.phone')
            ->join('dymanic_category t2', 't2.id = t1.category_id', 'LEFT')
            ->join('user t3', 't3.id = t1.userid', 'LEFT')
            ->where($where)
            ->order('t1.dy_id ' . $order)
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    //添加文章
    public function add()
    {
        $category = Db::name('dymanic_category')->select();
        $this->assign('category', get_tree_option1($category, 0));

        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if ($post['type'] == 1) {
                if (!$post['userid']) {
                    return ['err' => '请填写发布用户'];
                }
            } else if (!$post['type']) {
                if (!$post['content'] && !$post['masterimg']) {
                    return ['err' => '请填写内容或上传照片'];
                }
                $post['category_id'] = 0;
            }

            if (!$id) { //添加数据

                //压缩图集
                $sumbImage = [];
                if (isset($post['masterimg']) && $post['masterimg']) {
                    $masterimg = explode(',', $post['masterimg']);
                    foreach ($masterimg as $k => $v) {
                        $v = explode('.', $v);
                        $sumbImage[$k] = $v[0] . '_thumb.' . $v[1];
                    }
                    $sumbImage = implode(',', $sumbImage);
                } else {
                    $sumbImage = '';
                }

                $post['sumbImage'] = $sumbImage;

                $db = Db::name('dymanic')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据
                if (isset($post['masterimg'])) {
                    $post['masterimg'] = explode(',', trim($post['masterimg'], '{}'));

                    $post['masterimg'] = str_replace('"', '', $post['masterimg']);

                    //压缩图集
                    $sumbImage = [];
                    if ($post['masterimg']) {
                        $masterimg = $post['masterimg'];
                        foreach ($masterimg as $k => $v) {
                            if ($v) {
                                $v = explode('.', $v);
                                $sumbImage[$k] = $v[0] . '_thumb.' . $v[1];
                            } else {
                                unset($post['masterimg'][$k]);
                            }
                        }
                        $sumbImage = implode(',', $sumbImage);
                    } else {
                        $sumbImage = '';
                    }

                    //图集
                    $post['masterimg'] = implode(',', $post['masterimg']);
                    $post['sumbImage'] = $sumbImage;
                }

                $db = Db::name('dymanic')->where('dy_id', $id)->update($post);

                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('dymanic')->where('dy_id', $id)->find();

                $name['masterimg'] = json_encode(explode(',', $name['masterimg']));

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    // 下面跳转链接
    public function add1()
    {
        $url = url('article/add', ['mychannel' => '1', 'url' => '-1']);
        $this->redirect($url);
    }

    public function add2()
    {
        $url = url('article/add', ['mychannel' => '2', 'url' => '-1']);
        $this->redirect($url);
    }

    public function add3()
    {
        $url = url('article/add', ['mychannel' => '3', 'url' => '-1']);
        $this->redirect($url);
    }

    //删除文章
    public function del()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $res = Db::name('dymanic')->where(['dy_id'=>$id])->find();
                $db = Db::name('dymanic')->delete($id);
                if ($db) {
                    $images = $imagesa = $imagesb = [];
                    if($res['sumbImage']){
                        $imagesa = explode(',', $res['sumbImage']);
                    }
                    if($res['sumbImage']){
                        $imagesb = explode(',', $res['masterimg']);
                    }
                    $images = array_unique(array_merge($imagesa, $imagesb));
                    foreach ($images as $key => $value) {
                        \app\service\AliOss::delete($value);
                    }
                    if ($res['video']) {
                        \app\service\AliOss::delete($res['video']);
                    }
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    // 批量更新排序
    public function desAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            foreach ($_POST['des'] as $k => $v) {
                $id = intval($k);
                $name = intval($v);
                Db::name('article')->where('id', $id)->setField('des', $name);
            }
            $data = ['ret' => '更新排序成功'];
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }

    // 批量删除
    public function delAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $db = Db::name('dymanic')->delete($post);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => '删除失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }

    // 批量设置hide
    public function all()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            $type = input('type');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $db = Db::name('article');
                foreach ($post as $k => $v) {
                    if ($type == 'del') {
                        //   echo "删除成功";
                        $db->delete($v);
                    } else {
                        $db->where('id', $v)->setField('hide', $type);
                    }
                }
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => '删除失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }

    // 自定义属性
    public function flags()
    {
        $data = Db::name('flags')->order('id asc')->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function flagsAdd()
    {
        $id = input("id");
        if (request()->isAjax()) {
            $post = input('post.');;
            if ($post) {
                $time = time();
                $post['update_time'] = $time; //更新时间
                if (!$id) {   // 添加数据
                    $titledb = Db::name('flags')->where('title', $post['title'])->find();
                    if ($titledb) {
                        return ['err' => '标题已存在'];
                    }
                    $post['create_time'] = $time; // 添加时间
                    $db = Db::name('flags')->insert($post);
                    if ($db) {
                        $data = ['ret' => '添加成功'];
                    } else {
                        $data = ['err' => '添加失败'];
                    }
                } else {      //修改数据
                    $db = Db::name('flags')->where('id', $id)->update($post);
                    if ($db) {
                        $data = ['ret' => '修改成功'];
                    } else {
                        $data = ['err' => '修改失败'];
                    }
                }
            } else {
                $data = ["err" => 'post错误'];
            }
        } else {
            if ($id) {
                $name = Db::name('flags')->where('id', $id)->find();
                //var_dump($name);die();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除自定义属性
    public function flagsDel()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $admin = Db::name('article')->where('flags', $id)->find();
                if (!$admin) {
                    $db = Db::name('flags')->delete($id);
                    if ($db) {
                        $data = ['ret' => '删除成功'];
                    } else {
                        $data = ['err' => '删除失败'];
                    }
                } else {
                    $data = ['err' => '属性下有文章，请先删除文章对应属性'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }
    // 显示 隐藏文章
    // public function hide(){
    //     $id=input('id');
    //     if(request()->isAjax()){
    //         if($id){
    //             $arra=['0'=>'隐藏','1'=>'显示'];
    //             $type='hide';
    //             $db=Db::name('article')->where('id',$id)->value('hide');
    //             if($db==1){
    //                 $hide=0;
    //             }else{
    //                 $hide=1;
    //             }
    //             $db=Db::name('article')->where('id',$id)->setField($type,$hide);
    //             if($db){
    //                 $data=['ret'=>$arra[$hide].'成功','id'=>$hide,'text'=>$arra[$hide]];
    //             }else{
    //                 $data=['err'=>$arra[$hide].'失败'];
    //             }
    //         }else{
    //             $data=['err'=>'ID参数错误'];
    //         }
    //     }else{
    //         $data=['err'=>'AJAX参数错误'];
    //     }
    //     return $data;
    // }
    //拒绝 审核 禁止 通过
    public function hide()
    {
        if (request()->isAjax()) {
            $id = input('id') ? input('id') : '0';
            $type = input('type') ? input('type') : '0';
            $text = ['0' => '<font color="#f00">禁止</font>', '1' => '<font color="#1ab394">通过</font>', '2' => '审核', '3' => '<font color="#f00">拒绝</font>'];
            if ($id) {
                // 投稿奖励用户
                $aritlce = Db::name('article')->where('id', $id)->find();
                if ($aritlce['uid']) {
                    if ($type == 0) {
                        _records($aritlce['uid'], '投稿文章ID：' . $aritlce['id'] . '管理员设置隐藏状态');
                    } else if ($type == 3) {
                        _records($aritlce['uid'], '投稿文章ID：' . $aritlce['id'] . '拒绝通过');
                    } else if ($type == 3) {
                        _records($aritlce['uid'], '投稿文章ID：' . $aritlce['id'] . '管理员设置审核状态');
                    }
                }
                if ($aritlce['uid'] && $type == 1) {
                    // 检测是否开启投稿
                    $data = DB::name('member_config')->where("name='articleAdd' or name='articleHide' or name='articleScore' or name='articleNum' or name='articleCode' or name='articleJingyan' or name='articleMoney'")->fetchSql(false)->select();
                    $articleAdd = $data['0']['text'];     //文章投稿
                    $articleHide = $data['1']['text'];    //投稿审核
                    $articleScore = $data['2']['text'];   //投稿奖励积分
                    $articleNum = $data['3']['text'];     //每天投稿限制
                    $articleCode = $data['4']['text'];    //投稿文章开启验证码
                    $articleJingyan = $data['5']['text'];   //投稿奖励积分
                    $articleMoney = $data['6']['text'];   //投稿奖励积分
                    unset($data);   // 销毁变量
                    // 读取会员配置 - 结束
                    // 检测金额奖励
                    if ($articleMoney) {
                        // 检测是否已奖励，防止重复奖励
                        $aritlcejiance = Db::name('member_records')->where(['type' => 'money', 'text' => '投稿奖励ID：' . $aritlce['id'], 'data' => '+'])->value('id');
                        if (!$aritlcejiance) {
                            _records($aritlce['uid'], '投稿奖励ID：' . $aritlce['id'], $articleMoney, 'money', '+');
                            Db::name('member')->where('id', $aritlce['uid'])->setInc('money', $articleMoney);
                        }
                    }
                    // 检测积分奖励
                    if ($articleScore) {
                        // 检测是否已奖励，防止重复奖励
                        $aritlcejiance = Db::name('member_records')->where(['type' => 'score', 'text' => '投稿奖励ID：' . $aritlce['id'], 'data' => '+'])->value('id');
                        if (!$aritlcejiance) {
                            _records($aritlce['uid'], '投稿奖励ID：' . $aritlce['id'], $articleScore, 'score', '+');
                            Db::name('member')->where('id', $aritlce['id'])->setInc('score', $articleScore);
                        }
                    }
                    // 检测经验值奖励
                    if ($articleJingyan) {
                        $aritlcejiance = Db::name('member_records')->where(['type' => 'jingyan', 'text' => '投稿奖励ID：' . $aritlce['id'], 'data' => '+'])->value('id');
                        if (!$articleJingyan) {
                            _records($aritlce['uid'], '投稿奖励ID：' . $aritlce['id'], $articleJingyan, 'jingyan', '+');
                            Db::name('member')->where('id', $this->member['id'])->setInc('jingyan', $articleJingyan);
                        }
                    }
                    _records($aritlce['uid'], '投稿文章ID：' . $aritlce['id'] . '审核通过');
                }
                $db = Db::name('article')->where('id', $aritlce['id'])->setField('hide', $type);
                if ($db) {
                    $data = [$text[$type]];
                } else {
                    $data = ['删除失败'];
                }
            } else {
                $data = ['GET值错误'];
            }
        } else {
            $data = ['提交错误'];
        }
        return $data;
    }

    // 审核投稿文章
    public function review()
    {
        $map['hide'] = ['in', '2,3,4'];
        $data = Db::name('article')->where($map)->order('des desc,id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function reviewadd()
    {
        $id = input("id/d");
        if (request()->isAjax()) {
            $post = input('post.');

            // $user=Db::name('article')->where('id',$id)->find();
            if ($post['hide'] == 3) {
                if (input('yuanyin') != null) {
                    $str = input('yuanyin');
                } else {
                    $str = '投稿被拒绝';
                }
                $data = [
                    'hide' => $post['hide'],
                    'yuanyin' => $str,
                ];
            } elseif ($post['hide'] == 4) {
                if (input('yijian') != null) {
                    $str = input('yijian');
                } else {
                    $str = '请重新编辑';
                }
                $data = [
                    'hide' => $post['hide'],
                    'yijian' => $str,
                ];
            }

            $db = Db::name('article')->where('id', $id)->update($data);
            if ($db !== false) {
                $data = ['ret' => '修改成功'];
            } else {
                $data = ['err' => '修改失败'];
            }

        } else {
            if ($id) {
                $name = Db::name('article')->where(['id' => $id])->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function watch()
    {
        if (!input('?id')) {
            $this->error("参数错误");
        }
        $id = input('id/d');
        $name = Db::name('dymanic')->where(['dy_id' => $id])->find();

        if ($name['masterimg']) {
            $name['masterimg'] = explode(',', $name['masterimg']);
        }
        
        if ($name['video'] && $name['enroll']) {
            $name['video'] = changeUrl($name['video'], 1);
        }

        // 增加点击次数 结束

        /*if($name['content']){
            // $name['content'] = stripslashes($name['content']);
            // $name['content']=str_replace('src="','src="'._imgUrl().'',$name['content']);
            // $name['content']=str_replace('<div>','',$name['content']);
            // $name['content']=str_replace('</div>','',$name['content']);
            preg_match_all("/img(.*?)src=\"(.*?)\"/", stripslashes($name['content']),$content);
           
            foreach ($content[2] as $k => $v) {
                if(strstr($v,'http')){
                  //  $db['content']=str_replace($v,$v,$db['content']);
        
                }else if(strpos($v,'/public/uploads/us/') !== false){
                    // $db['content']=str_replace($v,'../image/loadingImage.png" Tapmode onclick="img('.$k.');" ffxiang-src="'.$config['url'].$v.'" id="ffxiangImgCache',$db['content']);
                 
                }else{
                    $name['content']=str_replace($v,_imgUrl().$v,stripslashes($name['content']));
                  
                }   
            }
        }
        if($name['mychannel'] == 2){
        //     if($name['weitoutiao']==0){
                $content='';
                foreach (json_decode($name['images'],true) as $k => $v) {
                    $content.='<p class="a-image"><img src="'._imgUrl().$v['img'].'"></p>';
                    $content.='<p class="a-image">'.$v['img_text'].'</p>';
                }
                $name['content']="<p>".$name['description']."</p>".$content;
        //     }
        }*/
        // 读取会员信息
        // $user=Db::name('user')->where('id',$name['uid'])->find();
        // 分类导航
        $typeid = Db::name('classify')->where(['id' => $name['state']])->field('id,name')->find();
        $this->assign('typeid', $typeid);
        // $this->assign('user',$user);
        // 是否已收藏
        //  $shoucang=0;
        //  $name['guanzhu']=0;

        //  $name['shoucang']=$shoucang;

        //  $name['content']=str_replace('<div>','',$name['content']);
        // $content=preg_split('/<div class="y-box article-actions">/', $name['content'],-1);
        // // file_put_contents('./2.txt', $content[0]);
        //  $name['content']=$content[0];
        //  $content=preg_split('/<ul class="label-list list-paddingleft-2">/', $name['content'],-1);
        //   $name['content']=$content[0];
        //   $content=preg_split('/<p><strong>延伸阅读/', $name['content'],-1);
        //   $name['content']=$content[0];

        // var_dump($content);exit();
        // $this->assign('ping',$ping);
        $this->assign('name', $name);
        return $this->fetch();
    }


    // 评论管理
    public function ping()
    {
        $shenhe = input('shenhe/d');
        
        if ($shenhe === null) {
            $shenhe = 1;
        }
        $where['t1.shenhe'] = $shenhe;
        $this->assign('shenhe', $shenhe);


        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if(in_array($search_type, ['userid', 'dy_id'])){
                $where['t1.'.$search_type] = $search_name;
            }elseif(in_array($search_type, ['phone'])){
                $where['t2.'.$search_type] = ['like', '%'.$search_name.'%'];
            }else{
                $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
            }
        }

        $start = input('start');
        $end = input('end');

        if ($start && $end) {
            $where['t1.addtime'] = ['between', [$start, $end]];
        } else if ($start && !$end) {
            $where['t1.addtime'] = ['egt', $start];
        } else if (!$start && $end) {
            $where['t1.addtime'] = ['elt', $end];
        }
        $this->assign('start', $start);
        $this->assign('end', $end);

        $order = input('order') ? input('order') : 'desc';
        if ($order == 1) {
            $order = 'desc';
        } else if ($order == 2) {
            $order = 'asc';
        }

        $data = Db::name('dycomment t1')->field('t1.*,t2.name,t2.role,t2.phone,t2.sex')->join('user t2', 't2.id = t1.userid')->where($where)->order('t1.comment_id '.$order)->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function ($item)
        {
            $item['in_temp'] = Db::name('dycomment_template')->where('binary content ="'.addslashes($item['content']).'"')->fetchSql(false)->find();
            return $item;
        });

        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }
    //动态处理
    public function pingshenhe()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            $dycomment = db('dycomment')->where('comment_id', $id)->find();
            if ($id && $dycomment) {
                $dymanic = Db::name('dymanic')->where(['dy_id' => $dycomment['dy_id']])->find();
                $db = db('dycomment')->where('comment_id', $id)->update(['shenhe' => $post['shenhe'], 'shenhe_time' => time(), 'shenhe_admin_id'=>$this->adminInfo['id']]);
                if($post['shenhe'] != $dycomment['shenhe']){
                    if($post['shenhe'] == 1){
                        Db::name('dymanic')->where(['dy_id' => $dycomment['dy_id']])->setInc('comments');
                        Db::name('user')->where(['id' => $dymanic['userid']])->setInc('charm_value', 2);


                        $touserid = $dymanic['userid'];
                        $user_id = $dycomment['userid'];
                        $dy_id = $dymanic['dy_id'];
                        if ($touserid && $touserid != $user_id && $dymanic['state'] == 0 && ($dymanic['addway']==0 || ($dymanic['addway']==2&&$dymanic['userid']==$touserid))) {
                            $user = _user($user_id);
                            $message = [
                                'type' => 17,
                                'to_user' => $touserid,
                                'context' => json_encode([
                                                'name' => $user['name'],
                                                'head' => $user['head_100'],
                                                'dy_id' => $dy_id,
                                                'content'=>$dycomment['content'],
                                                'comment_id'=>$dycomment['comment_id']
                                            ], JSON_UNESCAPED_UNICODE),
                                'uid' => $user['id'],
                                'user_id'=>$dy_id
                            ];

                            Db::name('sys_message')->insert($message);


                            $Gatewaymessage = json_encode([
                                "code" => 200,
                                "action" => 'api/Privatechat/interactionCount',
                                'data' => []
                            ]);

                            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $Gatewaymessage);
                        }

                    }else{
                        Db::name('dymanic')->where(['dy_id' => $dycomment['dy_id']])->setDec('comments');
                    }
                }
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ["err" => '参数缺失'];
            }
        }
        return $data;
    }
    // 批量设置hide
    public function shenhePingAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            $type = input('type');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $db = Db::name('dycomment');
                $timenow = time();
                if ($type == 'temp') {
                    $contents = Db::name('dycomment')->where(['comment_id'=>['in',$post]])->column('content');
                    $contents = array_filter(array_unique($contents));
                    $inTemps = Db::name('dycomment_template')->where('binary content in ("'.implode('","',$contents).'")')->fetchSql(false)->column('content');
                    $newTemps = array_diff($contents, $inTemps);
                    $inserts = [];
                    foreach ($newTemps as $key => $value) {
                        $inserts[] = [
                            'content'=>$value,
                            'time'=>$timenow
                        ];
                    }

                    if (sizeof($inserts)){
                        $db = Db::name('dycomment_template')->insertAll($inserts);
                    }
                } else {
                    foreach ($post as $k => $v) {
                        $dycomment = $db->where('comment_id', $v)->find();
                        if ($type == 'del') {
                            //   echo "删除成功";
                            $db->delete($v);
                            if($dycomment['shenhe'] == 1){
                                Db::name('dymanic')->where(['dy_id' => $dycomment['dy_id']])->setDec('comments');
                            }
                        } else {
                            $db->where('comment_id', $v)->update(['shenhe'=>$type, 'shenhe_time'=>$timenow, 'shenhe_admin_id'=>$this->adminInfo['id']]);
                            if($type != $dycomment['shenhe']){
                                if($type == 1){
                                    Db::name('dymanic')->where(['dy_id' => $dycomment['dy_id']])->setInc('comments');

                                    $dymanic = Db::name('dymanic')->find($dycomment['dy_id']);
                                    $touserid = $dymanic['userid'];
                                    $user_id = $dycomment['userid'];
                                    $dy_id = $dycomment['dy_id'];
                                    if ($touserid && $touserid != $user_id && $dymanic['state'] == 0 && ($dymanic['addway'] == 0||($dymanic['addway'] == 2&&$dymanic['userid'] == $touserid))) {
                                        $user = _user($user_id);
                                        $message = [
                                            'type' => 17,
                                            'to_user' => $touserid,
                                            'context' => json_encode([
                                                            'name' => $user['name'],
                                                            'head' => $user['head_100'],
                                                            'dy_id' => $dy_id,
                                                            'content'=>$dycomment['content'],
                                                            'comment_id'=>$dycomment['comment_id']
                                                        ], JSON_UNESCAPED_UNICODE),
                                            'uid' => $user['id'],
                                            'user_id'=>$dy_id
                                        ];

                                        Db::name('sys_message')->insert($message);


                                        $Gatewaymessage = json_encode([
                                            "code" => 200,
                                            "action" => 'api/Privatechat/interactionCount',
                                            'data' => []
                                        ]);

                                        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $Gatewaymessage);
                                    }

                                }else if($dycomment['shenhe'] == 1){
                                    Db::name('dymanic')->where(['dy_id' => $dycomment['dy_id']])->setDec('comments');
                                }
                            }
                        }
                    }
                }
                if ($db) {
                    $data = ['ret' => '操作成功'];
                } else {
                    $data = ['err' => '操作失败'];
                }
            } else {
                $data = ['err' => '操作失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }


    // 修改/查看被评论
    public function pingadd()
    {
        $id = input("id/d");
        if (request()->isAjax()) {
            if ($id) {   // 添加数据
                $db = Db::name('dymanic')->where('dy_id', $id)->update($post);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('dycomment')->where('comment_id', $id)->find();
                $article = Db::name('dymanic')->where('dy_id', $name['dy_id'])->find();
                // $pingList=Db::name('comment')->where('tid',$id)->order('id desc')->paginate(_getCachePages(),false,['query'=>request()->param()]);
                // $page = $pingList->render();

                if ($name['touserid']) {
                    $pingList = Db::name('dycomment')->where('comment_id', $name['touserid'])->order('comment_id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

                    $prev = 1;
                    $page = $pingList->render();
                } else {
                    $pingList = Db::name('dycomment')->where('touserid', $name['comment_id'])->order('comment_id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
                    $prev = 0;
                    $page = $pingList->render();
                }
                $this->assign('page', $page);
                if ($name) {
                    $this->assign('article', $article);
                    $this->assign('name', $name);
                    $this->assign('pingList', $pingList);
                    $this->assign('prev', $prev);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    // 评论删除
    public function pingDel()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                /*                $db=Db::name('article_ping')->delete($id);
                                if($db){
                                    $data=['ret'=>'删除成功'];
                                }else{
                                    $data=['err'=>'删除失败'];
                                }*/
                //如果$prev为1，则是二级评论；为0，则是一级评论，除了删除本条评论，还要删除下面的二级评论
                // if(input('type')){

                $dycomment = Db::name('dycomment')->where(['comment_id' => $id])->find();

                $db = Db::name('dycomment')->delete($id);
                // }else {
                //     $db=Db::name('dycomment')->delete($id);
                //     $db=Db::name('dycomment')->where('tid',$id)->delete();                    
                // }
                if ($db) {
                    if ($dycomment['shenhe'] == 1) {
                        Db::name('dymanic')->where(['dy_id' => $dycomment['dy_id']])->setDec('comments');
                    }

                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    // 评论删除 下
    public function pingXaiDel()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = Db::name('dycomment')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    // 举报管理
    public function jubao()
    {
        $where = [];

        $state = input('state');
        if ($state !== null) {
            $where['state'] = $state;
        }


        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if (in_array($search_type, ['user_id', 'report_user'])) {
                $where[$search_type] = $search_name;
            } else if (in_array($search_type, ['name', 'phone']) && $search_name) {
                $userids = Db::name('user')->where([$search_type => ['like', '%'.$search_name.'%']])->column('id');
                $where['user_id'] = ['in', $userids];
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $start = input('start');
        $end = input('end');

        if ($start && $end) {
            $where['time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $where['time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['time'] = ['elt', strtotime($end)];
        }
        $this->assign('start', $start);
        $this->assign('end', $end);

        $data = Db::name('report_user')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function($item){
            $item['admin_name'] = Db::name('admin')->where(['id'=>$item['admin_id']])->cache(300)->value('name');
            $item['data'] = $item['data'] ? json_decode($item['data'], true) : [];
            $item['datalastest'] = sizeof($item['data']) ? $item['data'][sizeof($item['data']) - 1] : null;
            $item['jubaocount'] = Db::name('report_user')->where(['user_id'=>$item['user_id'],'report_user'=>$item['report_user']])->cache(10)->count();
            return $item;
        });

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);

        $this->assign('state', $state);

        return $this->fetch();
    }

    public function jubaoDel()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                /*                $db=Db::name('article_ping')->delete($id);
                                if($db){
                                    $data=['ret'=>'删除成功'];
                                }else{
                                    $data=['err'=>'删除失败'];
                                }*/
                //如果$prev为1，则是二级评论；为0，则是一级评论，除了删除本条评论，还要删除下面的二级评论
                // if(input('type')){
                $db = Db::name('report_user')->delete($id);
                // }else {
                //     $db=Db::name('dycomment')->delete($id);
                //     $db=Db::name('dycomment')->where('tid',$id)->delete();
                // }
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    /**
     * 举报处理
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function jubaoadd()
    {
        $admin = Session::get('admin', 'mmjtAdmin');
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            $name = Db::name('report_user')->find($id);
            if($name){
                $name['data'] = $name['data'] ? json_decode($name['data'], true) : [];
            }else{
                return ["err" => '举报不存在'];
            }

            array_push($name['data'], ['admin_id'=>$admin['id'], 'admin_name'=>$admin['name'], 't'=>time(), 'v'=>'结束处理']);

            $update = ['data'=>json_encode($name['data'], JSON_UNESCAPED_UNICODE), 'state'=>1];
            if(!$name['admin_id']){
                $update['admin_id'] = $admin['id'];
            }

            $db = Db::name('report_user')->where(['id'=>$name['id']])->update($update);

            if ($db) {
                $data = ['ret' => '修改成功'];
            } else {
                $data = ['err' => '修改失败'];
            }
        }
        return $data;
    }
    public function dealJubao()
    {
        $admin = Session::get('admin', 'mmjtAdmin');
        $id = input('id');
        $name = Db::name('report_user')->find($id);
        if($name){
            $name['data'] = $name['data'] ? json_decode($name['data'], true) : [];
            foreach ($name['data'] as $key => $value) {
                $name['data'][$key]['images'] = isset($value['imgs']) && $value['imgs'] ? explode(',', $value['imgs']) : [];
            }
        }else{
            return ["err" => '举报不存在'];
        }
        if (request()->isAjax()) {
            $remark = input('post.remark');
            if(!$remark) {
                return ["err" => '请填写处理描述'];
            }
            $images = input('post.masterimg');
            array_push($name['data'], ['admin_id'=>$admin['id'], 'admin_name'=>$admin['name'], 't'=>time(), 'v'=>$remark, 'imgs'=>$images]);

            $update = ['data'=>json_encode($name['data'], JSON_UNESCAPED_UNICODE), 'state'=>2];
            if(!$name['admin_id']){
                $update['admin_id'] = $admin['id'];
            }

            $db = Db::name('report_user')->where(['id'=>$name['id']])->update($update);

            if ($db) {
                $data = ['ret' => '修改成功'];
            } else {
                $data = ['err' => '修改失败'];
            }
        }else{
            $read = input('read', 0);
            $this->assign('read', $read);
            
            $this->assign('name', $name);
            $data = $this->fetch();
        }
        return $data;
    }

    // 举报回复
    public function jubaoHuifu()
    {
        if (request()->isAjax()) {
            $id = input('id');
            $content = input('content');
            if ($id) {
                $db = Db::name('jubao')->where('id', $id)->find();
                if ($db) {
                    $adminId = Session::get('admin', 'mmjtAdmin');
                    $where['uid'] = $db['uid'];
                    $where['aid'] = $db['aid'];
                    $where['content'] = $content;
                    $where['time'] = time();
                    $where['admin_id'] = $adminId['id'];
                    $db = Db::name('jubao')->insert($where);
                    if ($db) {
                        $data = ['ret' => '回复成功'];
                    } else {
                        $data = ['err' => '回复失败'];
                    }
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    // 单页广利
    public function page()
    {
        $data = Db::name('page')->where(['sys_channel'=>['in', [0,1]]])->order('id asc')->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    // 添加单页
    public function pageadd()
    {
        $id = input("id");
        if (request()->isAjax()) {
            $post = input('post.');
            $post['body'] = Request::instance()->post('body','','htmlspecialchars');

            if (!isset($post['body']) || !$post['body']) {
                return ['err' => '内容不能为空'];
            }

            $post['sys_channel'] = 1;
            $post['body'] = in_content($post['body']);

            if (!$id) {   // 添加数据

                $db = Db::name('page')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {      //修改数据
                if ($post['id'] != $id) {
                    $has = Db::name('page')->find($post['id']);
                    if ($has) return ['err'=>'ID 已存在'];
                }
                $db = Db::name('page')->where('id', $id)->update($post);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('page')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    // 删除单页
    public function pagedel()
    {
        $id = input("id");
        $db = Db::name('page')->delete($id);
        if ($db) {
            $data = ['ret' => '删除成功'];
        } else {
            $data = ['err' => '删除失败'];
        }

        return $data;
    }

    // 动态分类
    public function category()
    {
        $where = [];
        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $category = Db::name('dymanic_category')->where($where)->field('id,name,parent_id tid,des,image,create_time,update_time,is_hide,is_rec')->order('des desc,id asc')->select();
        if (empty($where)) {
            $category = get_tree_option($category, 0);
        } else {
            foreach ($category as &$value) {
                $value['depth'] = false;
            }
        }
        $this->assign('data', $category);
        return $this->fetch();
    }

    // 删除动态分类
    public function delCategory()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = db('dymanic_category')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    // 添加动态分类
    public function addcategory()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');;

            //开始验证
            $validate = new Validate([
                ['name', 'require|max:30', '名称不能为空|长度不能超过30字符']
            ]);

            $data = [
                'name' => $post['name']
            ];

            if ($validate->check($data)) {
                if (!$id) {  //添加数据
                    $typename = db('dymanic_category')->where(['name' => $post['name']])->find();
                    if ($typename) {
                        return ['err' => '名称已存在'];
                    }
                    $time = time();
                    $post['create_time'] = $time;
                    $post['update_time'] = $time;

                    // if (!$post['image']) {
                    //     return ['err' => '请先上传图标'];
                    // } else {

                    // }


                    $res = db('dymanic_category')->insert($post);
                    if ($res) {
                        $data = ['ret' => '添加成功'];
                    } else {
                        $data = ['err' => '添加失败'];
                    }
                } else {//修改数据
                    $res = db('dymanic_category')->where('id', $id)->update($post);
                    if ($res) {
                        $data = ['ret' => '修改成功'];
                    } else {
                        $data = ['err' => '修改失败'];
                    }
                }
            } else {
                $data = ["err" => $validate->getError()];
            }
        } else {
            $tid = input('tid',0);
            if ($id) {
                $name = db('dymanic_category')->where('id', $id)->find();

                if ($name) {
                    if ($name['parent_id']) {
                        $tid = $name['parent_id'];
                    }
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $this->assign('tid', $tid);

            $data = $this->fetch();
        }

        return $data;
    }

    //动态处理
    public function authadd()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if ($id) {
                $dy = db('dymanic')->where('dy_id', $id)->find();
                $db = db('dymanic')->where('dy_id', $id)->update(['shenhe' => $post['shenhe'], 'reason' => $post['reason'], 'shenhe_time' => time(), 'admin_id'=>$this->adminInfo['id']]);

                if ($db) {
                    if ($post['shenhe'] == 1) {
                        Task::finish('dymanic_day', $dy['userid'], 2);
                    }
                    // if ($post['shenhe'] == 1) {
                    //     $category = \app\service\BaiduApi::GetCategory($dy['title'],$dy['content']);
                    //     $category_id = 0;
                    //     if ($category) {
                    //         $category_id = \app\api\model\DymanicSystemCategory::getCateId($category);
                    //     }

                    //     $keywords = \app\service\BaiduApi::GetKeyword($dy['title'],$dy['content']);
                    //     $topic_ids = [];
                    //     if ($keywords) {
                    //         foreach ($keywords as $k => $v) {
                    //             $topic_ids[] = \app\api\model\Topic::getTopicId($v);
                    //         }
                    //     }
                    //     $topic_ids = implode(',',$topic_ids);
                    //     db('dymanic')->where('dy_id', $id)->update(['system_topic_ids' => $topic_ids, 'system_category_id' => $category_id]);
                    // }
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ["err" => '参数缺失'];
            }
        }
        return $data;
    }

    // 批量设置hide
    public function shenheAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            $type = input('type');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $db = Db::name('dymanic');
                foreach ($post as $k => $v) {
                    if ($type == 'del') {
                        //   echo "删除成功";
                        $res = Db::name('dymanic')->where(['dy_id'=>$v])->find();
                        $dbres = $db->delete($v);
                        if ($dbres) {
                            $images = $imagesa = $imagesb = $imagesc = $imagesd = [];
                            if($res['sumbImage']){
                                $imagesa = explode(',', $res['sumbImage']);
                            }
                            if($res['masterimg']){
                                $imagesb = explode(',', $res['masterimg']);
                            }
                            if($res['video']){
                                $imagesc = explode(',', $res['video']);
                            }
                            if($res['cover']){
                                $imagesd = explode(',', $res['cover']);
                            }
                            $images = array_unique(array_merge($imagesa, $imagesb, $imagesc, $imagesd));
                            foreach ($images as $key => $value) {
                                \app\service\AliOss::delete($value);
                            }
                        }
                    } else {
                        $dy = Db::name('dymanic')->where(['dy_id'=>$v])->find();
                        $update = [
                            'shenhe'    =>  $type,
                            'admin_id'=>$this->adminInfo['id']
                        ];
                        if ($type == 2) {
                            $update['shenhe'] = 1;
                            $update['class'] = 1;
                        }

                        if ($update['shenhe'] == 1) {
                            Task::finish('dymanic_day', $dy['userid'], 2);
                        }

                        // if ($update['shenhe'] == 1) {
                        //     $category = \app\service\BaiduApi::GetCategory($dy['title'],$dy['content']);
                        //     $category_id = 0;
                        //     if ($category) {
                        //         $category_id = \app\api\model\DymanicSystemCategory::getCateId($category);
                        //     }

                        //     $keywords = \app\service\BaiduApi::GetKeyword($dy['title'],$dy['content']);
                        //     $topic_ids = [];
                        //     if ($keywords) {
                        //         foreach ($keywords as $keyword) {
                        //             $topic_ids[] = \app\api\model\Topic::getTopicId($keyword);
                        //         }
                        //     }
                        //     $topic_ids = implode(',',$topic_ids);
                        //     $update['system_topic_ids'] = $topic_ids;
                        //     $update['system_category_id'] = $category_id;
                        // }
                        $res = $db->where('dy_id', $v)->update($update);
                    }
                }
                if ($res) {
                    $data = ['ret' => '操作成功'];
                } else {
                    $data = ['err' => '操作失败'];
                }
            } else {
                $data = ['err' => '操作失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }

    // 动态评论
    public function comment()
    {
        $id = input("id/d");
        if (request()->isAjax()) {
            $post = input('post.');
            $post['dy_id'] = $id;

            $result = Db::name('dycomment')->insert($post);

            if ($result) {
                Db::name('dymanic')->where(['dy_id' => $id])->setInc('comments');

                $return = ['ret' => '评论成功'];
            } else {
                $return = ['err' => '评论失败'];
            }
        } else {
            $return = $this->fetch();
        }
        return $return;
    }
    
    
    public function dymanic()
    {
        $typeiddb = Db::name('dymanic_category')->where('is_hide', 0)->order('des desc,id asc')->select();
        $this->assign('typeid', $typeiddb);
        $rejects = Db::name('template_reject_reason')->where('type', 1)->order('sort desc,id asc')->select();
        $this->assign('rejects', json_encode($rejects, JSON_UNESCAPED_UNICODE));
        
        $where = [];
        $type = input('type');
        if ($type === null) {
            $type = 1;
        }
        
        if ($type) {
            $where['t1.type'] = $type - 1;
        }
        
        $this->assign('type', $type);
        
        $shenhe = input('shenhe/d');
        
        if ($shenhe === null) {
            // $shenhe = 1;
        } else {
            $where['t1.shenhe'] = $shenhe;
        }
        $this->assign('shenhe', $shenhe);

        $class = input('class/d', 1);
        if ($class) {
            $where['t1.class'] = $class;
            $this->assign('class', $class);
        }

        $addway = input('addway');
        if ($addway || $addway === '0') {
            $where['t1.addway'] = $addway > 0 ? ['>',0] : 0;
            $this->assign('addway', $addway);
        }
        
        
        $typeid = input('param.search_typeid');
        $search_name = input('param.search_name');
        if ($search_name) {
            if ($typeid == 'citys') {
                $where['t1.citys'] = ['like', '%' . $search_name . '%'];
            }elseif (in_array($typeid, ['userid','dy_id'])) {
                $where['t1.'.$typeid] = $search_name;
            } else if ($typeid == 'phone') {
                $where['t3.'.$typeid] = $search_name;
            }else {
                $where['t1.content|t1.title'] = ['like', '%' . $search_name . '%'];
            }
        }
        $order = input('order') ? input('order') : 'desc';
        if ($order == 1) {
            $order = 'desc';
        } else if ($order == 2) {
            $order = 'asc';
        }
        
        if ($typeid && $typeid != 'citys' && $typeid != 'userid' && $typeid != 'dy_id') {
            $where['t1.category_id'] = $typeid;
        }
        
        $data = Db::name('dymanic t1')
            ->field('t1.*, t2.name, t3.id, t3.name username, t3.phone, t3.sex, t3.age, t3.role, t3.entertainment,t3.reg')
            ->join('dymanic_category t2', 't2.id = t1.category_id', 'LEFT')
            ->join('user t3', 't3.id = t1.userid', 'LEFT')
            ->where($where)
            ->order('t1.dy_id ' . $order)
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function($item){
                $item['masterimg'] = explode(',', $item['masterimg']);
                $item['masterimg'] = $item['masterimg'][0] ? $item['masterimg'] : [];
                $class_types = ['','普通','经验'];
                $item['class_text'] = $class_types[$item['class']];
                $source_types = ['','小目标打卡','地点打卡','发布服务','发布邀约','','私密电台','抖音导入','快手导入'];
                $item['source_type_text'] = $source_types[$item['source_type']];
                $item['user_attestation'] = false;
                if ($item['class'] == 2) {
                    $category = Db::name('user_attestation')->where(['user_id'=>$item['userid']])->column('category');
                    if ($category) {
                        $category = implode(',',$category);
                        $item['user_attestation'] = Db::name('topic')->where(['id'=>['in',$category]])->column('name');
                        $item['user_attestation'] = $item['user_attestation'] ? '#'.implode('#', $item['user_attestation']) : '未认证';
                    }
                }
                if ($item['video'] && $item['enroll']) {
                    $item['video'] = changeUrl($item['video'], 1);
                }

                if ($item['sex'] == '男') {
                    $topup = Db::name('user_data')->where(['user_id'=>$item['userid']])->value('topup');
                    $topup = floatval($topup);
                    $item['valueText'] = $topup ? '' : '未充值';
                } else {
                    $withdraw = Db::name('withdraw')->where(['userid'=>$item['userid'], 'state'=>['in', [0,1]]])->find();
                    $item['valueText'] = $withdraw ? '' : '未提现';
                }
                return $item;
            });
        
        $page = $data->render();
        $this->assign('search_typeid', $typeid);
        $this->assign('data', $data);
        $this->assign('page', $page);
        
        return $this->fetch();
    }
    
    //添加文章
    public function addDymanic()
    {
        $category = Db::name('dymanic_category')->select();
        $this->assign('category', get_tree_option1($category, 0));
        
        $id = input("id");
        $topic = Db::name('topic')->order('is_rec desc, sort desc, id desc')->column('id','name');
        
        if (request()->isAjax()) {
            $post = input('post.');
            $post['type'] = $post['type'] ?? 0;
            if ($post['type'] == 1) {
                if (!$post['userid']) {
                    return ['err' => '请填写发布用户'];
                }
            } else if (!$post['type']) {
                if (!$post['content'] && !$post['masterimg']) {
                    return ['err' => '请填写内容或上传照片'];
                }
                $post['category_id'] = 0;
            }
            
            $post['topic'] = $post['topic'] ? '#'.implode('#', $post['topic']) : '';
            $post['topic_experience'] = $post['topic_experience'] ? '&'.implode(' &', $post['topic_experience']) : '';

            if (!$id) { //添加数据
                
                //压缩图集
                $sumbImage = [];
                if ($post['masterimg']) {
                    $masterimg = explode(',', $post['masterimg']);
                    foreach ($masterimg as $k => $v) {
                        $v = explode('.', $v);
                        $sumbImage[$k] = $v[0] . '_thumb.' . $v[1];
                    }
                    $sumbImage = implode(',', $sumbImage);
                } else {
                    $sumbImage = '';
                }
                
                $post['sumbImage'] = $sumbImage;
                
                $db = Db::name('dymanic')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据
                $post['masterimg'] = explode(',', trim($post['masterimg'], '{}'));
                
                $post['masterimg'] = str_replace('"', '', $post['masterimg']);
                
                //压缩图集
                $sumbImage = [];
                if ($post['masterimg']) {
                    $masterimg = $post['masterimg'];
                    foreach ($masterimg as $k => $v) {
                        if ($v) {
                            $v = explode('.', $v);
                            $sumbImage[$k] = $v[0] . '_thumb.' . $v[1];
                        } else {
                            unset($post['masterimg'][$k]);
                        }
                    }
                    $sumbImage = implode(',', $sumbImage);
                } else {
                    $sumbImage = '';
                }
                
                //图集
                $post['masterimg'] = implode(',', $post['masterimg']);
                $post['sumbImage'] = $sumbImage;
                
                $db = Db::name('dymanic')->where('dy_id', $id)->update($post);
                
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('dymanic')->where('dy_id', $id)->find();
                
                $name['masterimg'] = json_encode(explode(',', $name['masterimg']));
                
                if ($name) {
                    $name['topic'] = $name['topic'] ? array_unique(array_filter(explode('#', substr($name['topic'], 1)))) : [];
                    $name['topic_experience'] = $name['topic_experience'] ? array_unique(array_filter(explode('&', substr($name['topic_experience'], 1)))) : [];

                    $name['show_video'] = changeUrl($name['video']);
                    if ($name['video'] && $name['enroll']) {
                        $name['show_video'] = changeUrl($name['video'], 1);
                    }
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $topic = Db::name('topic')->order('is_rec desc, sort desc, id desc')->column('id,name');
            $this->assign('topic', $topic);
            $data = $this->fetch();
        }
        return $data;
    }


    public function categoryEdit()
    {
        $id = input("id");
        $t = db('dymanic_category')->where('parent_id', 0)->order('des desc,id asc')->select();
        $checkeddb = db('dymanic')->where('dy_id', $id)->value('cate_children');
        $checkeddb = $checkeddb ? explode(',', $checkeddb) : [];
        $html = '';
        foreach ($t as $k => $v) {
            $html .= '<h5>' . $v['name'] . '<a style="color:skyblue;margin-left:20px;" onClick="add(\''.url('addcategory',['tid'=>$v['id'], 'url'=>-1]).'\')">添加下级分类</a></h5>';
            $html .= '<div class="form-group">';
            $html .= '<div class="col-sm-10">';
            $html .= '<div class="radio i-checks">';
            $t2 = db('dymanic_category')->where('parent_id', $v['id'])->order('des desc,id asc')->select();
            if ($t2) {
                foreach ($t2 as $v2) {
                    $checked = '';
                    if ($id) {
                        foreach ($checkeddb as $cv) {
                            if ($cv == $v2['id']) {
                                $checked = 'checked';
                                break;
                            }
                        }
                    }
                    $html .= '<label class="col-md-3"><input type="checkbox" ' . $checked . ' value="' . $v2['id'] . '" name="data[]">' . $v2['name'] . '</label>';
                }
            }
                $html .= '</div></div></div>';
        }
        $this->assign('dymanic_category', $html);
        if (request()->isAjax()) {

            $post = input('post.');;
            if (!input('?post.data')) {
                $dataname = false;
            } else {
                $dataname = $post['data'];
            }
            if ($dataname) {
                $cate = implode(',', $dataname);
                $top_Cate = Db::name('dymanic_category')->where(['id'=>['in',$cate]])->value('parent_id');
                $db = db('dymanic')->where('dy_id', $id)->update(['cate_children' => $cate, 'category_id'=>$top_Cate]);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ['err' => '最少选一个类别'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }


    public function searchtopic($keyword = '')
    {
        if ($keyword) {
            $topic = Db::name('topic')->where(['name'=>['like', '%'.$keyword.'%']])->field('id,name')->order('is_rec desc, sort desc, id desc')->select();
        } else {
            $topic = Db::name('topic')->field('id,name')->order('is_rec desc, sort desc, id desc')->select();
        }
        return json($topic);
    }




    // 动态分类
    public function topic()
    {
        $where = [];
        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = db('topic')->where($where)->order('is_rec desc, sort desc, id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }

    // 删除动态分类
    public function deltopic()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = db('topic')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    // 添加动态分类
    public function addtopic()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');;

            //开始验证
            $validate = new Validate([
                ['name', 'require|max:30', '名称不能为空|长度不能超过30字符']
            ]);

            $data = [
                'name' => $post['name']
            ];

            if ($validate->check($data)) {
                if (!$id) {  //添加数据
                    $typename = db('topic')->where(['name' => $post['name']])->find();
                    if ($typename) {
                        return ['err' => '名称已存在'];
                    }
                    $time = time();
                    $post['create_time'] = $time;
                    $post['update_time'] = $time;


                    $res = db('topic')->insert($post);
                    if ($res) {
                        $data = ['ret' => '添加成功'];
                    } else {
                        $data = ['err' => '添加失败'];
                    }
                } else {//修改数据
                    $res = db('topic')->where('id', $id)->update($post);
                    if ($res) {
                        $data = ['ret' => '修改成功'];
                    } else {
                        $data = ['err' => '修改失败'];
                    }
                }
            } else {
                $data = ["err" => $validate->getError()];
            }
        } else {
            if ($id) {
                $name = db('topic')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }

        return $data;
    }

    public function setTopicRec($id, $state)
    {
        $data = Db::name('topic')->where(['id'=>$id])->update(['is_rec'=>$state, 'update_time'=>time()]);

        return $data ? ['ret' => '操作成功'] : ['err' => '操作失败'];
    }
    public function categoryhide($id, $state)
    {
        $data = Db::name('dymanic_category')->where(['id'=>$id])->update(['is_hide'=>$state]);

        return $data ? ['ret' => '操作成功'] : ['err' => '操作失败'];
    }
    public function categoryrec($id, $state)
    {
        $data = Db::name('dymanic_category')->where(['id'=>$id])->update(['is_rec'=>$state]);

        return $data ? ['ret' => '操作成功'] : ['err' => '操作失败'];
    }



    public function searchHistory()
    {
        $where = [];
        $typeid = input('param.search_typeid');
        $search_name = input('param.search_name');
        if ($search_name) {
            $where['content'] = ['like', '%' . $search_name . '%'];
        }
        $order = input('order') ? input('order') : 'desc';
        if ($order == 1) {
            $order = 'desc';
        } else if ($order == 2) {
            $order = 'asc';
        }

        $data = Db::name('search_history')
            ->where($where)
            ->order('id ' . $order)
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }



    public function delSearchHistory($id)
    {
        $res = Db::name('search_history')->where(['id'=>['in',$id]])->delete();

        return $res ? ['ret' => '操作成功'] : ['err' => '操作失败'];
    }

    public function setDyLimit()
    {
        $dy_id = input('dy_id');
        $key = input('key');
        $value = input('value');
        $res = Db::name('dymanic')->where(['dy_id'=>$dy_id])->update([$key=>$value]);
        return $res ? ['ret' => '操作成功'] : ['err' => '操作失败'];
    }
}
